const formidable = require('formidable')
const path = require('path')

module.exports = function (req, uploadDir) {
  return new Promise((resolve, reject) => {
    const form = new formidable.IncomingForm()
    form.keepExtensions = true // 让上传的文件保存扩展名
    form.uploadDir = uploadDir // 设置上传文件的路径

    form.parse(req, (err, fields, files) => {
      if (err) {
        return reject(err)
      }
      fields.image = path.basename(files.image.path)
      resolve(fields)
    })
  })
}
